package base.common
{
	import flash.external.ExternalInterface;
	import flash.utils.Dictionary;

	public class JavaScriptManager
	{
		private var _asCallBackFunctionDic:Dictionary=new Dictionary();
		private static var _instance:JavaScriptManager;
		public static function get instance():JavaScriptManager
		{
			if(_instance == null)
			{
				_instance = new JavaScriptManager();
			}  
			return _instance;
		}
		
		public function JavaScriptManager()
		{
		}
		
		/**
		 *注册 
		 */		
		public function register():void
		{
			if(ExternalInterface.available)
			{
				ExternalInterface.addCallback("callAsFunction",callAsFunction);
			}
		}
		
		/**
		 *调用JS方法 
		 * @param type 标识类型
		 * @param jsFunction jS方法名
		 * @param asCallBackFunction as回调方法名
		 * @param jsParameters 传递给js的参数
		 * 
		 */		
		public function call(type:int, jsFunction:String, asCallBackFunction:Function=null, jsParameters:Object=null):void
		{
			if(ExternalInterface.available)
			{
				if(asCallBackFunction!=null)
				{
					_asCallBackFunctionDic[type]=asCallBackFunction;
				}
				if(jsParameters!=null)
				{
					ExternalInterface.call(jsFunction, type, jsParameters);
				}
				else
				{
					ExternalInterface.call(jsFunction, type);
				}
			}
		}
		
		/**
		 *js调用as的回调方法 
		 * @param type 标识类型
		 * @param asParameters 传递给as的参数，Json格式数据
		 */		
		public function callAsFunction(type:int, asParameters:Object):void
		{
			if(_asCallBackFunctionDic[type]!=null)
			{
				var asCallBackFunction:Function=_asCallBackFunctionDic[type] as Function;
				asCallBackFunction(asParameters);
				delete _asCallBackFunctionDic[type];
			}
		}
	}
}